<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Balance;
use App\Models\Withdraw;
use App\Services\BalanceService;
use Illuminate\Http\Request;
use Yansongda\Pay\Exceptions\GatewayException;

class WithdrawController extends BaseController
{

    public function index(Request $request) {
        $search = ['status' => -1, 'start_at' => '', 'end_at' => '', 'merchant_id' => ''];
        $input = $request->input();
        $deal_start_at = $input['deal_start_at'] ?? null;
        $deal_end_at = $input['deal_end_at'] ?? null;
        $benefit_user = $input['benefit_user'] ?? null;

        $users = Withdraw::apply($search, $input)
            ->when($deal_start_at, function ($q) use($deal_start_at){
                $q->where('updated_at', '>=', $deal_start_at);
            })
            ->when($benefit_user, function ($q) use($benefit_user) {
                $q->where('benefit_user', $benefit_user);
            })
            ->when($deal_end_at, function ($q) use($deal_end_at){
                $end_at = date('Y-m-d', strtotime($deal_end_at) + 24 * 3600);
                return $q->where('updated_at', '<', $end_at);
            })
            ->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));
        return $this->paginate($users);
    }

    public function handle(Request $request) {
        $this->validate($request, [
            'id' => 'required',
            'action' => 'required|in:pass,reject'
        ]);
        $input = $request->input();
        $model = Withdraw::find($input['id']);
        if (!$model)
            return $this->failed('提现id不存在');
        if ($input['action'] == 'reject') {
//            $this->validate($request, [
//                'reason' => 'required'
//            ]);
            if ($model->status != Withdraw::STATUS_TO_DO)
                return $this->failed('当前状态不是待审核状态');

            $model->reason = $input['reason'] ?? '';
            $model->status = Withdraw::STATUS_FAIL;
            $model->save();
            return $this->success([], '操作成功');
        }

        if ($model->status != Withdraw::STATUS_TO_DO)
            return $this->failed('当前状态不是待审核状态');

        $order = [
            'out_biz_no' => $model->trade_no,
            'trans_amount' => format_yuan($model->amount),
            'product_code' => 'TRANS_ACCOUNT_NO_PWD',
            'biz_scene' => 'DIRECT_TRANSFER',
            'payee_info' => [
                'identity' => $model->alipay_account,
                'identity_type' => 'ALIPAY_LOGON_ID',
                'name' => $model->realname
            ]
        ];
        try {
            $model->status = Withdraw::STATUS_ING;
            if ($model->save()) {
                $response =  $this->payApp()->transfer($order);
                \DB::transaction(function () use($model, $response) {
                    $model->status = Withdraw::STATUS_SUCCESS;
                    $model->out_order_id = $response->order_id;
                    $model->reason = $response->status;
                    $model->save();
                    BalanceService::store($model->benefit_user, 0, $model->merchant_id, -$model->amount, Balance::TYPE_WITHDRAW, 0, '', '', false, $model->id);
                });
            }
            return $this->success([], '提现成功');
        } catch (GatewayException $e) {
            $msg = $e->raw['alipay_fund_trans_uni_transfer_response']['sub_msg'];
            $model->status = Withdraw::STATUS_FAIL;
            $model->reason = $msg;
            $model->save();
            return $this->failed($msg);
        } catch (\Exception $e) {
            \Log::error($e->getMessage());
            return $this->failed($e->getMessage());
        }
    }


    public function query(Request $request) {
        $this->validate($request, [
            'trade_no' => 'required'
        ]);
        $input = $request->input();
        $model = Withdraw::where('trade_no', $input['trade_no'])->where('status', Withdraw::STATUS_ING)->first();
        if (!$model)
            return $this->failed('交易编号不存在');
        try {
            $response =  $this->payApp()->find(['out_biz_no' => $input['trade_no'], 'product_code' => 'TRANS_ACCOUNT_NO_PWD'
            , 'biz_scene' => 'DIRECT_TRANSFER'], 'transfer');
            \DB::transaction(function () use($model, $response) {
                $model->status = Withdraw::STATUS_SUCCESS;
                $model->out_order_id = $response->order_id;
                $model->reason = $response->status;
                $model->save();
                BalanceService::store($model->benefit_user, 0, $model->merchant_id, -$model->amount, Balance::TYPE_WITHDRAW, 0, '','', false, $model->id);
            });

            return $this->success([], '交易成功');
        } catch (GatewayException $e) {
            $msg = $e->raw['alipay_fund_trans_order_query_response']['sub_msg'];
            $model->status = Withdraw::STATUS_FAIL;
            $model->reason = $msg;
            $model->save();
            return $this->failed($msg);
        }
    }

    /**
     * Yansongda\Supports\Collection {#626
    #items: array:7 [
    "code" => "10000"
    "msg" => "Success"
    "order_id" => "20200623110070000006470065464532"
    "out_biz_no" => "1592907086"
    "pay_fund_order_id" => "20200623110070001506470071051937"
    "status" => "SUCCESS"
    "trans_date" => "2020-06-23 18:11:26"
    ]
    }
     */




}

